package vip.liux.gateway.utils;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;

public class ServerHttpRequestUtils {

    public static String getClientIp(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();

        // 从 X-Forwarded-For 请求头中获取
        String ip = request.getHeaders().getFirst("X-Forwarded-For");
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim(); // 如果有多个 IP，取第一个
        }

        // 如果 X-Forwarded-For 为空，则尝试从 X-Real-IP 获取
        if (ip == null || ip.isEmpty()) {
            ip = request.getHeaders().getFirst("X-Real-IP");
        }

        // 如果仍然为空，则从远程地址获取
        if (ip == null || ip.isEmpty()) {
            ip = request.getRemoteAddress() != null ? request.getRemoteAddress().getAddress().getHostAddress() : null;
        }

        return ip;
    }

    public static String buildQueryParamsString(MultiValueMap<String, String> queryParams) {
        StringBuilder builder = new StringBuilder();
        queryParams.forEach((key, values) -> {
            if (!builder.isEmpty()) {
                builder.append("&");
            }
            builder.append(key).append("=").append(String.join(",", values));
        });
        return builder.toString();
    }
}